package com.yinuo.listener;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.yinuo.entity.LinuxShellCmd;
import com.yinuo.common.CacheManage;
import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.stereotype.Component;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

/**
 * 加载documents文件夹下的数据
 */
//弃用的类
//@Component
public class StartApplicationListener implements ApplicationListener<ContextRefreshedEvent>{
 
	protected Logger log = LoggerFactory.getLogger(StartApplicationListener.class);

    @Override
	public void onApplicationEvent(ContextRefreshedEvent event) {
		log.info(String.format("load file content into cache"));
		InputStream in = null;
		try {
			in = StartApplicationListener.class.getResourceAsStream(CacheManage.LINUX_SHELL_CMD_PATH);
			String jsonStr = IOUtils.toString(in,"utf-8");
			JSONArray jarr = JSON.parseArray(jsonStr);
			List<Object> linuxCmds = new ArrayList<Object>(50);
			for(int i = 0;i<jarr.size();i++){
				JSONObject jobj = (JSONObject) jarr.get(i);
				LinuxShellCmd lsc = new LinuxShellCmd();
				lsc.setKey(jobj.getString("key"));
				lsc.setCmd(jobj.getString("cmd"));
				lsc.setCmdDesc(jobj.getString("cmdDesc"));
				lsc.setExample(jobj.getString("example"));
				lsc.setExampleDesc(jobj.getString("exampleDesc"));
				linuxCmds.add(lsc);
			}
			CacheManage.cache.put(CacheManage.LINUX_SHELL_CMD,linuxCmds);
			log.info("load file content into cache success");
			log.info(String.format("linux_shell_cmd file has %d rows data",linuxCmds.size()));
		} catch (Exception e) {
			log.error("load file content into cache faild",e);
		} finally {
			try{
				if(in!=null)in.close();
			}catch (Exception e){}
		}
	}
 
}